import logging.config

import flask_cors
from flask import Flask
from werkzeug.exceptions import HTTPException

from common.exchanges import DeribitPriService
from common.exchanges.base import ExchangeError
from common.exchanges.manager import ExchangeServiceManager
from web import settings, init_db_app
from web.common.error_code import GreeksApiError
from web.common.resp import fail_resp
from web.scheduler import init_scheduler
from web.views import bp

logger = logging.getLogger('web')

app = Flask('web')
app.config.from_object(settings)
flask_cors.CORS(app, supports_credentials=True)


@app.errorhandler(GreeksApiError)
def handle_greeks_api_error(e: GreeksApiError):
    return e.to_resp()


@app.errorhandler(ExchangeError)
def handle_greeks_api_error(e: ExchangeError):
    return fail_resp(e.code, message=e.msg)


@app.errorhandler(HTTPException)
def handler_http_error(e: HTTPException):
    return e.description, e.code


@app.errorhandler(Exception)
def handle_base_error(e):
    logger.exception(f'handle request failed: {e}')
    return fail_resp(500, message=f'web error: {e}', http_status_code=500)


def register_router(_app: Flask):
    _app.register_blueprint(blueprint=bp)


# 初始化数据库
init_db_app(app)

# 注册路由
register_router(app)


def init_app(es=True, scheduler=False):
    # 交易所service相关
    DeribitPriService.install_broker_info(
        settings.CONFIG_PARSER.get(f'exchange:deribit', 'client_id'),
        settings.CONFIG_PARSER.get(f'exchange:deribit', 'client_secret'),
    )

    if es:
        ExchangeServiceManager.config(env=settings.EXCHANGE_ENV, logger=logger)

        # 初始化exchange pub service
        ExchangeServiceManager.init_pub_service(
            settings.SUPPORT_EXCHANGES, settings.SUPPORT_BASE_CURRENCIES, settings.SUPPORT_MARGIN_CURRENCIES
        )

    # 调度器
    if scheduler:
        init_scheduler(app)
